package com.tsfyun.common.base.util;


import java.security.MessageDigest;
import java.util.*;

/**
 * @since Created in 2019/11/6 11:46
 */
public class EncryUtil {

    public static String generateSign(String appSecret, final HashMap requestMap) throws Exception {
        //Key值排序
        Collection<String> keySet = requestMap.keySet();
        List<String> list = new ArrayList<String>(keySet);
        Collections.sort(list);
        //组装签名字符串
        StringBuffer signStr = new StringBuffer();
        for (int i = 0, size = list.size(); i < size; i++) {
            String key = list.get(i);
            String value = StringUtils.null2EmptyWithTrim(requestMap.get(key));
            if (Objects.equals("sign", key)) {
                continue;
            }
            //参数值为空，则不参与签名
            if (value.length() > 0) {
                signStr.append(key).append("=").append(value).append("&");
            }
        }
        signStr.append("appSecret" + "=").append(appSecret);
        //MD5签名
        String mySign = md5Encrypt(signStr.toString());
        String sign = mySign.toUpperCase();
        return sign;
    }

    /**
     * 生成 MD5
     *
     * @param data 待处理数据
     * @return MD5结果
     */
    public static String md5Encrypt(String data) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] array = md.digest(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }


}
